package com.ete.app.ui.main

import android.app.Application
import androidx.databinding.ObservableInt
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import com.ete.app.R
import com.ete.service.manager.ManagerConstant
import com.ete.service.manager.location.LocationManager
import com.ete.service.util.DeviceUtils
import com.jkkc.lib.base.core.BaseModel
import com.jkkc.lib.base.core.BaseViewModel
import com.jkkc.lib.base.extend.BOOLEAN_FALSE
import com.jkkc.lib.base.extend.BOOLEAN_TRUE
import com.jkkc.lib.base.extend.TIME_TWO_SECOND
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Author:LiXian
 * <p>
 * Desc:TODO
 * Version:1.0
 * date 2024/1/8 9:55
 */
class MainViewModel(mApp: Application) : BaseViewModel<BaseModel>(mApp) {

    val mGpsIcon: ObservableInt = ObservableInt(R.mipmap.login_ic_gps_error2)

    private var isLocation = BOOLEAN_FALSE
    private var mLocationJob: Job? = null

    fun initLocationMode() {
        val resultCode = LocationManager.startLocation()
        ToastUtils.showShort(LocationManager.getErrorByCode(resultCode))
        if (!DeviceUtils.isHT930) return
        isLocation = BOOLEAN_TRUE
        mLocationJob = viewModelScope.launch(Dispatchers.IO) {
            while (isLocation) {
                val isGpsModel = LocationManager.isGpsModel()
                withContext(Dispatchers.Main) {
                    if (isGpsModel) {
                        mGpsIcon.set(R.mipmap.login_ic_gps_normal2)
                    } else {
                        mGpsIcon.set(R.mipmap.login_ic_gps_error2)
                    }
                }
                delay(TIME_TWO_SECOND)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        cancelLocation()
    }

    private fun cancelLocation() {
        isLocation = BOOLEAN_FALSE
        mLocationJob?.cancel()
        mLocationJob = null
    }
}